import 'dart:typed_data';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:daf/components/toast.dart';
import 'package:daf/global.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:daf/iconfont.dart';

class QrCodePage extends StatefulWidget {
  QrCodePage({Key key}) : super(key: key);
  @override
  _QrCodePageState createState() => _QrCodePageState();
}

class _QrCodePageState extends State<QrCodePage> {
  GlobalKey globalKey = GlobalKey();
  List<Uint8List> images = List();
  String _qrcodeText = 'https://www.baidu.com/s?ie=UTF-8&wd=Enzyme工具盒子';
  String _qrcodeBuildText = '';
  String _descText = '扫描二维码查看详情';
  TextEditingController _qrcodeTextController = TextEditingController();
  TextEditingController _descTextController = TextEditingController();

  @override
  void initState() {
    super.initState();
  }

  Future<Uint8List> _capturePng() async {
    try {
      RenderRepaintBoundary boundary =
          globalKey.currentContext.findRenderObject();
      var image = await boundary.toImage(pixelRatio: 3.0);
      ByteData byteData = await image.toByteData(format: ImageByteFormat.png);
      Uint8List pngBytes = byteData.buffer.asUint8List();
      var status = await Permission.storage.status;
      print(status.isUndetermined);
      final result = await ImageGallerySaver.saveImage(pngBytes,
          quality: 100, name: "工具箱-二维码-qrcode");
      Toast.show(context,
          msg: '二维码保存${result['isSuccess'] ? "成功" : "失败"}', duration: 1);
    } catch (e) {
      print(e);
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    _qrcodeTextController.text = _qrcodeText;
    _descTextController.text = _descText;
    return Scaffold(
      appBar: AppBar(
        title: Text(
          '二维码生成',
          style: TextStyle(
            fontSize: 16,
            color: Global.backgroundColor,
            fontWeight: FontWeight.bold,
          ),
        ),
        iconTheme: IconThemeData(
          color: Global.backgroundColor,
        ),
        elevation: 0,
        backgroundColor: Color.fromARGB(255, 94, 86, 237),
      ),
      body: Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        padding: EdgeInsets.fromLTRB(20, 10, 20, 10),
        child: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '请输入需要转为二维码的文字',
                style: TextStyle(
                  color: Global.fontColor,
                  fontSize: 15,
                  fontWeight: FontWeight.w600,
                ),
              ),
              SizedBox(height: 5),
              Container(
                padding: EdgeInsets.all(7),
                width: MediaQuery.of(context).size.width - 40,
                decoration: BoxDecoration(
                  color: Global.fontSecondColor.withOpacity(.1),
                  border: Border.all(
                    color: Global.fontSecondColor.withOpacity(.5),
                    width: .5,
                  ),
                  borderRadius: BorderRadius.circular(4),
                ),
                child: ConstrainedBox(
                  constraints: BoxConstraints(
                    maxWidth: MediaQuery.of(context).size.width - 40,
                  ),
                  child: TextField(
                    maxLines: 3,
                    controller: _qrcodeTextController,
                    style: TextStyle(
                      color: Global.fontColor,
                      fontSize: 14,
                    ),
                    decoration: InputDecoration.collapsed(
                      hintText: '请输入需要转为二维码的文字',
                      hintStyle: TextStyle(
                        color: Global.fontSecondColor.withOpacity(0.5),
                        fontSize: 14,
                      ),
                    ),
                    onChanged: (text) {
                      setState(() {
                        _qrcodeText = text;
                      });
                    },
                  ),
                ),
              ),
              SizedBox(height: 15),
              Text(
                '请输入底部介绍文字',
                style: TextStyle(
                  color: Global.fontColor,
                  fontSize: 15,
                  fontWeight: FontWeight.w600,
                ),
              ),
              SizedBox(height: 5),
              Container(
                padding: EdgeInsets.all(7),
                width: MediaQuery.of(context).size.width - 40,
                decoration: BoxDecoration(
                  color: Global.fontSecondColor.withOpacity(.1),
                  border: Border.all(
                    color: Global.fontSecondColor.withOpacity(.5),
                    width: .5,
                  ),
                  borderRadius: BorderRadius.circular(4),
                ),
                child: ConstrainedBox(
                  constraints: BoxConstraints(
                    maxWidth: MediaQuery.of(context).size.width - 40,
                  ),
                  child: TextField(
                    maxLines: 3,
                    controller: _descTextController,
                    style: TextStyle(
                      color: Global.fontColor,
                      fontSize: 14,
                    ),
                    decoration: InputDecoration.collapsed(
                      hintText: '请输入底部介绍文字',
                      hintStyle: TextStyle(
                        color: Global.fontSecondColor.withOpacity(0.5),
                        fontSize: 14,
                      ),
                    ),
                    onChanged: (text) {
                      setState(() {
                        _descText = text;
                      });
                    },
                  ),
                ),
              ),
              SizedBox(height: 15),
              RaisedButton.icon(
                color: Color.fromARGB(255, 94, 86, 237),
                elevation: 0,
                icon: Icon(
                  Icons.qr_code,
                  color: Global.backgroundColor,
                ),
                label: Text(
                  '${_qrcodeBuildText == '' ? '生成' : '更新'}二维码',
                  style: TextStyle(
                    color: Global.backgroundColor,
                    fontSize: 13,
                  ),
                ),
                onPressed: () {
                  setState(() {
                    _qrcodeBuildText = _qrcodeText;
                  });
                },
              ),
              SizedBox(height: 15),
              _qrcodeBuildText == ''
                  ? Container()
                  : Container(
                      width: MediaQuery.of(context).size.width - 40,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          RepaintBoundary(
                            key: globalKey,
                            child: Container(
                              decoration: BoxDecoration(
                                  color: Color.fromARGB(255, 94, 86, 237)),
                              padding: EdgeInsets.all(40),
                              width: MediaQuery.of(context).size.width - 40,
                              child: Column(
                                children: [
                                  Container(
                                    decoration: BoxDecoration(
                                        color: Global.backgroundColor),
                                    child: QrImage(
                                      data: _qrcodeBuildText,
                                      version: QrVersions.auto,
                                      size: MediaQuery.of(context).size.width -
                                          120,
                                    ),
                                  ),
                                  SizedBox(height: 20),
                                  Container(
                                    width: 230,
                                    decoration: BoxDecoration(
                                      border: Border(
                                        bottom: BorderSide(
                                          color: Global.backgroundColor
                                              .withOpacity(.2),
                                        ),
                                      ),
                                    ),
                                  ),
                                  SizedBox(height: 20),
                                  Text(
                                    _descText,
                                    maxLines: 10,
                                    style: TextStyle(
                                      color: Global.backgroundColor,
                                      fontSize: 15,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                          RaisedButton.icon(
                            color: Color.fromARGB(255, 94, 86, 237),
                            elevation: 0,
                            icon: Icon(
                              Icons.save_alt,
                              color: Global.backgroundColor,
                            ),
                            label: Text(
                              '保存二维码图片',
                              style: TextStyle(
                                color: Global.backgroundColor,
                                fontSize: 13,
                              ),
                            ),
                            onPressed: () {
                              _capturePng();
                            },
                          ),
                        ],
                      ),
                    ),
              SizedBox(height: 35),
            ],
          ),
        ),
      ),
    );
  }
}
